# -*- coding: utf-8 -*-
# !/usr/bin/env python
import requests
import json


class FSBot:
    url_api = {
        "获取token": "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/",
        "普通消息": "https://open.feishu.cn/open-apis/bot/v2/hook/",
        "卡片消息": "https://open.feishu.cn/open-apis/message/v4/send/",
        "图片消息": "https://open.feishu.cn/open-apis/image/v4/put/",
        "电话转ID": "https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=",
        "邮箱转ID": "https://open.feishu.cn/open-apis/user/v1/batch_get_id?emails=",
        "获取群ID": "https://open.feishu.cn/open-apis/chat/v4/list",
        "插入数据": "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/%s/values_prepend",
        "删除数据": "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/%s/dimension_range",
        "合并单元格": "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/%s/merge_cells",
        "拆分单元格": "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/%s/unmerge_cells",
        "设置单元格格式": "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/%s/style",
    }

    def __init__(self, app):
        self.app = app  # app为机器人
        self.table = None  # 共享文档的table_id
        self.sheet = None  # 共享文档的sheet_id
        self.token = self.get_token()
        self.header = {
            "Authorization": self.token,
            "Content-Type": "application/json; charset=utf-8"
        }

    def get_token(self):
        """获取应用token"""
        url = self.url_api['获取token']
        headers = {"Content-Type": "text/plain"}
        r = requests.post(url, headers=headers, json=self.app)
        return "Bearer " + json.loads(r.text)['tenant_access_token']

    def phone_to_open_id(self, mobile):
        """增加数据，原始数据下移"""
        r = requests.get(self.url_api['电话转ID'] + str(mobile), headers=self.header)
        return json.loads(r.text)['data']['mobile_users'][str(mobile)][0]['open_id']

    def mail_to_open_id(self, email):
        """增加数据，原始数据下移"""
        r = requests.get(self.url_api['邮箱转ID'] + email, headers=self.header)
        return json.loads(r.text)['data']['email_users'][email][0]['open_id']

    def get_chat_id(self):
        r = requests.get(self.url_api['获取群ID'], headers=self.header)
        return r.text

    def send_card(self, users_mail, data):
        body = {
            "msg_type": "interactive",
            "email": users_mail,
            "card": data
        }
        r = requests.post(self.url_api['url_card'], json=body, headers=self.header)
        return r.text

    def send_markdown(self, chat_id, content):
        """content是一个列表[[内容1,需要@的人],[内容2,需要@的人]]
        content = [[{"tag": "text","text": "提醒的内容"}, {"tag": "at", "user_id": bot.mail_to_open_id('jiu_zhang@hunliji.com')}]]
        """
        body = {
            "chat_id": chat_id,
            "msg_type": "post",
            "content": {
                "post": {
                    "zh_cn": {"title": "数据核心表监控提醒",
                              "content": content},
                }
            }
        }
        r = requests.post(self.url_api['卡片消息'], json=body, headers=self.header)
        return r.text

    def use_table(self, table, sheet):
        self.table = table
        self.sheet = sheet
        return self

    def add_data(self, sheet_range="", values=[]):
        """增加数据，原始数据下移"""
        data = {
            "valueRange": {
                "range": self.sheet + sheet_range,
                "values": values
            }
        }
        r = requests.post(self.url_api['插入数据'] % self.table, headers=self.header, json=data)
        return r.text

    def del_data(self, major=0, start_index=1, end_index=1):
        """删除数据"""
        data = {
            "dimension": {
                "sheetId": self.sheet,
                "majorDimension": ['ROWS', 'COLUMNS'][major],
                "startIndex": start_index,
                "endIndex": end_index
            }
        }
        r = requests.delete(self.url_api['删除数据'] % self.table, headers=self.header, json=data)
        return r.text

    def union_cell(self, sheet_range, major=0):
        """合并单元格"""
        url = self.url_api['合并单元格'] % self.table
        data = {
            "range": self.sheet + sheet_range,
            "mergeType": ['MERGE_ALL', 'MERGE_ROWS', 'MERGE_COLUMNS'][major]
        }
        r = requests.post(url, headers=self.header, json=data)
        return r.text

    def split_cell(self, sheet_range):
        """拆分单元格"""
        data = {
            "range": self.sheet + sheet_range
        }
        r = requests.post(self.url_api['拆分单元格'] % self.table, headers=self.header, json=data)
        return r.text

    def set_style(self, sheet_range, kind):
        """设置单元格格式"""
        data = {
            "appendStyle": {
                "range": self.sheet + sheet_range,
                "style": kind
            }
        }
        r = requests.put(self.url_api['设置单元格格式'] % self.table, headers=self.header, json=data)
        return r.text
